import 'dart:convert';

import 'package:ai_desktop_eidtor/models/user_model.dart';
import 'package:ai_desktop_eidtor/routes/app_page.dart';
import 'package:ai_desktop_eidtor/util/string_util.dart';
import 'package:ai_desktop_eidtor/util/y_toast.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../models/BookChapterRepository.dart';
import 'login_state.dart';


class LoginLogic extends GetxController {
  final LoginState state = LoginState();

  TextEditingController nameField = TextEditingController();
  TextEditingController passwordField = TextEditingController();
  TextEditingController authorField = TextEditingController();

  UserModel userModel = UserModel();

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
    getLocalData();
  }

  void getLocalData() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    var data = await pref.getString(StringUtil.userModelKey);
    if (data != null) {
      userModel = UserModel.fromJson(jsonDecode(data));
      nameField.text = userModel.userName;
      passwordField.text = userModel.password;
      authorField.text = userModel.authorName;
      StringUtil.userModel = userModel;
      update();
    }
  }

  void login() async {
    if (authorField.text.isEmpty) {
      YToast.toast('请输入笔名');
      return;
    }
    if (nameField.text.isEmpty) {
      YToast.toast('请输入用户名');
      return;
    }
    if (passwordField.text.isEmpty) {
      YToast.toast('请输入密码');
      return;
    }

    try {
      // 第一步：初始化 Hive
      await BookChapterRepository.initializeHive();

      // 第二步：初始化数据库仓库
      await BookChapterRepository().init();

      print('Hive 初始化成功');


    } catch (e) {
      print('Hive 初始化失败: $e');
      // runApp(ErrorApp(error: e.toString()));
    }
    SharedPreferences pref = await SharedPreferences.getInstance();
    UserModel model = UserModel()
      ..authorName = authorField.text
      ..userName = nameField.text
      ..password = passwordField.text;
    pref.setString(StringUtil.userModelKey, jsonEncode(model.toJson()));
    Get.toNamed(RouteName.home);
  }
}
